<template>
	<el-tree-select v-model="inputVal" :check-strictly="configure.checkStrictly" :disabled="configure.disabled"
		:placeholder="configure.placeholder" :lazy="!!lazyLoad" :load="load" :props="config" @change="handleChange"
		@node-click="handleNodeClick" :clearable="props.configure.clearable == undefined ? true : props.configure.clearable">
		<el-option v-for="item in selectOptions" :key="item.value" :label="item.label" :value="item.value"
			:disabled="item.disabled" />
	</el-tree-select>
</template>

<script lang="ts" setup>
import { ref, watch } from "vue";
import { TreeOptionType, PyTreeSelectType } from "./type";

const props = defineProps<{
	modelValue: string | Date | number;
	configure: PyTreeSelectType;
}>();
const inputVal = ref(props.modelValue);

const emits = defineEmits(["update:modelValue", "onChange"]);
const selectOptions = ref([] as TreeOptionType[]);

const config = {
	label: "label",
	children: "children",
	isLeaf: "leaf",
};

const result = ref<Record<string, { label: any; value: any }>>({});

const lazyLoad = props.configure.lazyLoad;

const load = (node: any, resolve: any) => {
	if (node.level != 0) {
		result.value[node.level] = {
			label: node.data?.label,
			value: node.data?.value,
		};
	}

	if (node.isLeaf) return resolve([]);
	if (lazyLoad) {
		lazyLoad(node, resolve);
	}
};

//change事件
const handleChange = () => {
	const _val = getResult();
	props.configure.change && props.configure.change(inputVal.value as string, _val);
	console.log(_val, "ssssssssssssssssssss");
	emits("onChange", inputVal.value);
	emits("update:modelValue", inputVal.value);
};
const handleNodeClick = (_node1: any, node: any) => {
	if (node.level != 0) {
		result.value[node.level] = {
			label: node.data?.label,
			value: node.data?.value,
		};
	}
};
const getResult = () => {
	const key = props.configure.valueKeys || "object";
	const values = Object.values(result.value) as { label: any; value: any }[];
	if (key === "label") {
		return values.map(item => item.label);
	} else if (key === "value") {
		return values.map(item => item.value);
	} else {
		return values;
	}
};

const initSelectOptions = async () => {
	if (typeof props.configure.options == "function") {
		selectOptions.value = await props.configure.options();
	} else {
		selectOptions.value = props.configure.options || [];
	}
};

watch(
	() => props.modelValue,
	val => {
		inputVal.value = val;
	},
	{ deep: true }
);

watch(
	() => props.configure,
	() => {
		initSelectOptions();
	},
	{ deep: true }
);
</script>
